package cn.lh.exception;

import cn.lh.enums.GlobalErrorCode;
import cn.lh.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public JSONResult ExceptionHandler(Exception e) {
        log.info(e.getMessage());
        return JSONResult.error(GlobalErrorCode.SERVICE_ERROR.getMessage(), GlobalErrorCode.SERVICE_ERROR.getCode());
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult GlobalCustomExceptionHandler(GlobalCustomException e) {
        log.info(e.getErrorCode(), e.getErrorMessage());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.info(e.getMessage());
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        errors.forEach(item -> stringBuilder.append(item.getDefaultMessage()).append(";"));
        return JSONResult.error(stringBuilder.toString(), "10000");
    }
}
